package com.zkx.fssb.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;

import java.util.Map;

public class AlipayUtil {
    // 沙箱环境网关地址
//    private static final String ALIPAY_GATEWAY = "https://openapi.alipaydev.com/gateway.do";

//    private static final String ALIPAY_GATEWAY = "https://openapi.alipay.com/gateway.do";
    // 新版沙箱环境的网关地址
    private static final String ALIPAY_GATEWAY = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // 商户应用ID （我的沙箱应用ID）
    public static final String APP_ID = "9021000135661581";
    // 商户私钥 （我的应用私钥）
    public static final String APP_PRIVATE_KEY =
            "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCAvfq0t91rkJsLTA6KibKj2fQu3UyNc8XkQbTa2WdA/y9mbW+XG3Cb8fC/qNk4kI4fNy7PHs10BzGThhTG+Ac3ABUcztLUWuGRaIkHMf/9kz1aZhK3tLLymkuryIQA/0JAQ3JOb7w3HsEKhd8EYP0i+ARBPIC62EO4jOGrGgzeK8ZnnRLG/oO2PCXE7oA5H9wGmnjyh/2LekcICw/fQgK2YwMpVGwAQ6N3YkdGM+y4cO5C9I3z7O6GzjHVVDSYyiewUgPGevH2X/R4nUGzp9l5hcnnLZnS7cbwjO6xOITKvjnAv/fErBUv50VpakvfLhSgnJfPalAYXCZCf9Pw1zQtAgMBAAECggEAWde6aHlTbOhKOrUGBMoZP10vmbDX5nLfq+3qrzs+Yk5zHrDKShJdIIbTsny7sky20bPp16KwUANhJolQYJXgOxK0qRjwaj9N4PKphbrv4V7qVvaao1bX9pOUsTnKXQPFk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8d29s8lA2MLokJtcy31GGGoAgjmq0Q==";
    // 支付宝公钥 （我的沙箱支付宝公钥）
    public static final String ALIPAY_PUBLIC_KEY =
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhVszWC0BZ6Cgolx40oNdV5cGo3G3PAZBJ7KHhmFCoCs1w+DsJe/44VxpgouaKvJUmbBxrcX5XTDHBEL3m0/3a5HItXH9AHnAYZz1x//zRW631GuF1Ifej062xM1KJu0BxEbys4HuUshk+5osCVqojifZ6mLx+dANuYKh9UnWcGfv8uVctuBXoGPjFal+WHjpiaziDxxa0ZxcdfChyPlDWdnDJJoo8/iUWlHfJaqK8exgSRWNHtxx9WZnEyzxei/cNlASEh+FZYIZQw9hHBT1CLaFuZ8pscCSHRNhtJbPIgjT6DoO6Jr4zwbgutLojgH+e/rsAbDrbTkQIYVEmXQ1wQIDAQAB";

    // 支付宝同步通知地址
    private static final String RETURN_URL = "http://localhost:9600/server/payment/returnUrl";
    // 支付宝异步通知地址
    private static final String NOTIFY_URL = " http://hiunss.natappfree.cc/elm/payment/notifyUrl";


    // 编码格式
    public static final String CHARSET = "UTF-8";

    // 返回格式
    public static final String FORMAT = "json";

    // 签名类型
    public static final String SIGN_TYPE = "RSA2";

    public static AlipayClient getAlipayClient() {
        return new DefaultAlipayClient(ALIPAY_GATEWAY, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
    }

    /**
     * 调用支付宝的支付接口的核心方法
     * @param outTradeNo
     * @param totalAmount
     * @param subject
     * @param productCode - 支付交易的类型（电脑网站、手机网站）
     * @return
     * @throws AlipayApiException
     */
    public static String createPayOrder(String outTradeNo, String totalAmount,
                                        String subject, String productCode) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(totalAmount);
        model.setSubject(subject);
        model.setProductCode(productCode); // "FAST_INSTANT_TRADE_PAY"
        model.setBody("");
        request.setBizModel(model);

        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            return response.getBody();
        } else {
            throw new AlipayApiException("创建支付订单失败");
        }
    }

    public static String createMobilePayOrder(String outTradeNo, String totalAmount,
                                        String subject, String productCode) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(totalAmount);
        model.setSubject(subject);
        model.setProductCode(productCode);
        model.setBody("");
        request.setBizModel(model);

        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            return response.getBody();
        } else {
            throw new AlipayApiException("创建移动端支付订单失败");
        }
    }




    // 验证支付宝回调参数的签名
    public static boolean verify(Map<String, String> params) {
        try {
            // 调用SDK的验签方法进行签名验证
            // 这里的 alipayPublicKey 是你自己的支付宝公钥
            // 这里的 charset 是你使用的字符编码，一般为 UTF-8
            // 这里的 signType 是签名类型，一般为 RSA2
            boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE);

            return signVerified;
        } catch (AlipayApiException e) {
            // 处理异常，打印日志等
            e.printStackTrace();
            return false;
        }
    }
}
